{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "victorian-latitude",
   "metadata": {},
   "source": [
    "# Bike Share System"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "imported-table",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "electoral-turkey",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# install Pint if necessary\n",
    "\n",
    "try:\n",
    "    import pint\n",
    "except ImportError:\n",
    "    !pip install pint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "formal-context",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://raw.githubusercontent.com/AllenDowney/' +\n",
    "         'ModSimPy/master/modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "progressive-typing",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unlimited-antenna",
   "metadata": {},
   "source": [
    "This chapter presents a simple model of a bike share system and\n",
    "demonstrates the features of Python we'll use to develop simulations of real-world systems.\n",
    "\n",
    "Along the way, we'll make decisions about how to model the system. In\n",
    "the next chapter we'll review these decisions and gradually improve the model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "electronic-radius",
   "metadata": {},
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "above-denial",
   "metadata": {},
   "source": [
    "## Modeling a Bike Share System\n",
    "\n",
    "Imagine a bike share system for students traveling between Olin College and Wellesley College, which are about three miles apart in eastern Massachusetts.\n",
    "\n",
    "Suppose the system contains 12 bikes and two bike racks, one at Olin and one at Wellesley, each with the capacity to hold 12 bikes.\n",
    "\n",
    "As students arrive, check out a bike, and ride to the other campus, the number of bikes in each location changes. In the simulation, we'll need to keep track of where the bikes are. To do that, we'll use a function called `State`, which is defined in the ModSim library."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "incorrect-comparison",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare = State(olin=10, wellesley=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "living-wayne",
   "metadata": {},
   "source": [
    "The equations in parentheses create two variables, `olin` and `wellesley`, and give them the values `10` and `2`.\n",
    "The `State` function stores these variables and their values in a `State` object, which gets assigned to a new variable named `bikeshare`.\n",
    "\n",
    "Variables stored inside a `State` object are called *state variables*.\n",
    "In this example, the state variables represent the number of\n",
    "bikes at each location. Their values indicate that there are 10 bikes at Olin and 2 at Wellesley. \n",
    "\n",
    "The `State` object is assigned to a new variable named `bikeshare`.\n",
    "We can get the value of a variable in a `State` object using the *dot operator*, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "brief-diversity",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare.olin"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "intermediate-midwest",
   "metadata": {},
   "source": [
    "And this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "designed-brazilian",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare.wellesley"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "phantom-oklahoma",
   "metadata": {},
   "source": [
    "Or, to display all of the state variables and their values, you can enter just the name of the object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "impaired-potter",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "vital-journal",
   "metadata": {},
   "source": [
    "These values make up the *state* of the system."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fleet-beijing",
   "metadata": {
    "tags": []
   },
   "source": [
    "The ModSim library provides a function called `show` that displays a `State` object as a table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "basic-fabric",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "show(bikeshare)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "specified-definition",
   "metadata": {
    "tags": []
   },
   "source": [
    "You don't have to use `show`, but I think the results look better."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "delayed-ocean",
   "metadata": {},
   "source": [
    "We can update the state by assigning new values to the variables. \n",
    "For example, if a student moves a bike from Olin to Wellesley, we can figure out the new values and assign them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "floppy-trainer",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare.olin = 9\n",
    "bikeshare.wellesley = 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "natural-gossip",
   "metadata": {},
   "source": [
    "Or we can use *update operators*, `-=` and `+=`, to subtract 1 from\n",
    "`olin` and add 1 to `wellesley`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "hungarian-bride",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare.olin -= 1\n",
    "bikeshare.wellesley += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "radical-mills",
   "metadata": {},
   "source": [
    "The result is the same either way."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "controversial-opportunity",
   "metadata": {},
   "source": [
    "## Defining Functions\n",
    "\n",
    "So far we have used functions defined in NumPy and the ModSim library. Now we're going to define our own functions.\n",
    "\n",
    "When you are developing code in Jupyter, it is often efficient to write a few lines of code, test them to confirm they do what you intend, and then use them to define a new function. For example, these lines move a bike from Olin to Wellesley:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "vertical-drawing",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare.olin -= 1\n",
    "bikeshare.wellesley += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "approximate-rolling",
   "metadata": {},
   "source": [
    "Rather than repeat them every time a bike moves, we can define a new\n",
    "function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "significant-nutrition",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bike_to_wellesley():\n",
    "    bikeshare.olin -= 1\n",
    "    bikeshare.wellesley += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "generous-tracker",
   "metadata": {},
   "source": [
    "`def` is a special word in Python that indicates we are defining a new\n",
    "function. The name of the function is `bike_to_wellesley`. The empty\n",
    "parentheses indicate that this function requires no additional\n",
    "information when it runs. The colon indicates the beginning of an\n",
    "indented *code block*.\n",
    "\n",
    "The next two lines are the *body* of the function. They have to be\n",
    "indented; by convention, the indentation is four spaces.\n",
    "\n",
    "When you define a function, it has no immediate effect. The body of the\n",
    "function doesn't run until you *call* the function. Here's how to call\n",
    "this function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "moving-jurisdiction",
   "metadata": {},
   "outputs": [],
   "source": [
    "bike_to_wellesley()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "meaningful-christmas",
   "metadata": {},
   "source": [
    "When you call the function, it runs the statements in the body, which\n",
    "update the variables of the `bikeshare` object; you can check by\n",
    "displaying the new state."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "proper-symposium",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(bikeshare)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eleven-brook",
   "metadata": {},
   "source": [
    "When you call a function, you have to include the parentheses. If you\n",
    "leave them out, you get this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "identical-yacht",
   "metadata": {},
   "outputs": [],
   "source": [
    "bike_to_wellesley"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "premier-youth",
   "metadata": {},
   "source": [
    "This result indicates that `bike_to_wellesley` is a function. You don't have to know what `__main__` means, but if you see something like this, it probably means that you named a function but didn't actually call it.\n",
    "So don't forget the parentheses."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "brazilian-medicare",
   "metadata": {},
   "source": [
    "## Print Statements\n",
    "\n",
    "As you write more complicated programs, it is easy to lose track of what\n",
    "is going on. One of the most useful tools for debugging is the *print statement*, which displays text in the Jupyter notebook.\n",
    "\n",
    "Normally when Jupyter runs the code in a cell, it displays the value of\n",
    "the last line of code. For example, if you run:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "heavy-patrol",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare.olin\n",
    "bikeshare.wellesley"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ancient-projection",
   "metadata": {},
   "source": [
    "Jupyter runs both lines, but it only displays the value of the\n",
    "second. If you want to display more than one value, you can use\n",
    "print statements:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "french-preference",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(bikeshare.olin)\n",
    "print(bikeshare.wellesley)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "original-hollywood",
   "metadata": {},
   "source": [
    "When you call the `print` function, you can put a variable in\n",
    "parentheses, as in the previous example, or you can provide a sequence\n",
    "of variables separated by commas, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "alternative-keyboard",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(bikeshare.olin, bikeshare.wellesley)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "described-produce",
   "metadata": {},
   "source": [
    "Python looks up the values of the variables and displays them; in this\n",
    "example, it displays two values on the same line, with a space between\n",
    "them.\n",
    "\n",
    "Print statements are useful for debugging functions. For example, we can\n",
    "add a print statement to `bike_to_wellesley`, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "robust-holly",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bike_to_wellesley():\n",
    "    print('Moving a bike to Wellesley')\n",
    "    bikeshare.olin -= 1\n",
    "    bikeshare.wellesley += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "vital-lender",
   "metadata": {},
   "source": [
    "Each time we call this version of the function, it displays a message,\n",
    "which can help us keep track of what the program is doing.\n",
    "The message in this example is a *string*, which is a sequence of\n",
    "letters and other symbols in quotes.\n",
    "\n",
    "Just like `bike_to_wellesley`, we can define a function that moves a\n",
    "bike from Wellesley to Olin:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "fifteen-atmosphere",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bike_to_olin():\n",
    "    print('Moving a bike to Olin')\n",
    "    bikeshare.wellesley -= 1\n",
    "    bikeshare.olin += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "requested-glasgow",
   "metadata": {},
   "source": [
    "And call it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "matched-narrow",
   "metadata": {},
   "outputs": [],
   "source": [
    "bike_to_olin()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sitting-semiconductor",
   "metadata": {},
   "source": [
    "One benefit of defining functions is that you avoid repeating chunks of\n",
    "code, which makes programs smaller. Another benefit is that the name you\n",
    "give the function documents what it does, which makes programs more\n",
    "readable."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "enhanced-maintenance",
   "metadata": {},
   "source": [
    "## If Statements\n",
    "\n",
    "At this point we have functions that simulate moving bikes; now let's think about simulating customers. As a simple model of customer behavior, I will use a random number generator to determine when customers arrive at each station.\n",
    "\n",
    "The ModSim library provides a function called `flip` that generates random \"coin tosses\".\n",
    "When you call it, you provide a probability between 0 and 1, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "29c1f41a",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# this line sets the random number generator so the results in\n",
    "# the book are the same every time we run it\n",
    "np.random.seed(17)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "illegal-metropolitan",
   "metadata": {},
   "outputs": [],
   "source": [
    "flip(0.7)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "appropriate-funds",
   "metadata": {},
   "source": [
    "The result is one of two values: `True` with probability 0.7 (in this example) or `False`\n",
    "with probability 0.3. If you run `flip` like this 100 times, you should\n",
    "get `True` about 70 times and `False` about 30 times. But the results\n",
    "are random, so they might differ from these expectations.\n",
    "\n",
    "`True` and `False` are special values defined by Python. \n",
    "They are called *boolean* values because they are\n",
    "related to Boolean algebra (<https://modsimpy.com/boolean>).\n",
    "\n",
    "Note that they are not strings. There is a difference between `True`, which is a boolean value, and `'True'`, which is a string.\n",
    "\n",
    "We can use boolean values to control the behavior of the program, using an *if statement*:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "excessive-murder",
   "metadata": {},
   "outputs": [],
   "source": [
    "if flip(0.5):\n",
    "    print('heads')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "seventh-profile",
   "metadata": {},
   "source": [
    "If the result from `flip` is `True`, the program displays the string\n",
    "`'heads'`. Otherwise it does nothing.\n",
    "\n",
    "The syntax for `if` statements is similar to the syntax for\n",
    "function definitions: the first line has to end with a colon, and the\n",
    "lines inside the `if` statement have to be indented.\n",
    "\n",
    "Optionally, you can add an *else clause* to indicate what should\n",
    "happen if the result is `False`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "fundamental-nursing",
   "metadata": {},
   "outputs": [],
   "source": [
    "if flip(0.5):\n",
    "    print('heads')\n",
    "else:\n",
    "    print('tails')    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "recovered-chemical",
   "metadata": {},
   "source": [
    "If you run the previous cell a few times, it should print `heads` about half the time, and `tails` about half the time.\n",
    "\n",
    "Now we can use `flip` to simulate the arrival of customers who want to\n",
    "borrow a bike. Suppose students arrive at the Olin station every two\n",
    "minutes on average.\n",
    "In that case, the chance of an arrival during any one-minute period is 50%, and we can simulate it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "twenty-health",
   "metadata": {},
   "outputs": [],
   "source": [
    "if flip(0.5):\n",
    "    bike_to_wellesley()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "difficult-construction",
   "metadata": {},
   "source": [
    "If students arrive at the Wellesley station every three minutes, on average,\n",
    "the chance of an arrival during any one-minute period is 33%, and we can\n",
    "simulate it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "played-character",
   "metadata": {},
   "outputs": [],
   "source": [
    "if flip(0.33):\n",
    "    bike_to_olin()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "standard-party",
   "metadata": {},
   "source": [
    "We can combine these snippets into a function that simulates a *time step*, which is an interval of time, in this case one minute:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "ecological-colon",
   "metadata": {},
   "outputs": [],
   "source": [
    "def step():\n",
    "    if flip(0.5):\n",
    "        bike_to_wellesley()\n",
    "    \n",
    "    if flip(0.33):\n",
    "        bike_to_olin()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "amateur-exposure",
   "metadata": {},
   "source": [
    "Then we can simulate a time step like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "mediterranean-german",
   "metadata": {},
   "outputs": [],
   "source": [
    "step()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sought-mobile",
   "metadata": {},
   "source": [
    "Depending on the results from `flip`, this function might move a bike to Olin, or to Wellesley, or neither, or both."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "organic-proportion",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The previous version of `step` is fine if the arrival probabilities\n",
    "never change, but in reality they vary over time.\n",
    "\n",
    "So instead of putting the constant values 0.5 and 0.33 in `step`, we can replace them with *parameters*.\n",
    "Parameters are variables whose values are set when a function is called.\n",
    "\n",
    "Here's a version of `step` that takes two parameters, `p1` and `p2`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "hollywood-shopping",
   "metadata": {},
   "outputs": [],
   "source": [
    "def step(p1, p2):\n",
    "    if flip(p1):\n",
    "        bike_to_wellesley()\n",
    "    \n",
    "    if flip(p2):\n",
    "        bike_to_olin()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "encouraging-arkansas",
   "metadata": {},
   "source": [
    "The values of `p1` and `p2` are not set inside this function; instead,\n",
    "they are provided when the function is called, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "buried-alert",
   "metadata": {},
   "outputs": [],
   "source": [
    "step(0.5, 0.33)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aggregate-dynamics",
   "metadata": {},
   "source": [
    "The values you provide when you call the function are called\n",
    "*arguments*. The arguments, `0.5` and `0.33` in this example, get\n",
    "assigned to the parameters, `p1` and `p2`, in order. So running this\n",
    "function has the same effect as:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "recognized-denmark",
   "metadata": {},
   "outputs": [],
   "source": [
    "p1 = 0.5\n",
    "p2 = 0.33\n",
    "\n",
    "if flip(p1):\n",
    "    bike_to_wellesley()\n",
    "    \n",
    "if flip(p2):\n",
    "    bike_to_olin()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "raised-museum",
   "metadata": {},
   "source": [
    "The advantage of using parameters is that you can call the same function many times, providing different arguments each time.\n",
    "\n",
    "Adding parameters to a function is called *generalization*, because it makes the function more general; without parameters, the function always does the same thing; with parameters, it can do a range of things."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "scenic-african",
   "metadata": {},
   "source": [
    "## For Loops\n",
    "\n",
    "At some point you will get sick of running cells over and over.\n",
    "Fortunately, there is an easy way to repeat a chunk of code, the *for loop*. Here's an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "polish-river",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(3):\n",
    "    print(i)\n",
    "    bike_to_wellesley()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "compatible-conspiracy",
   "metadata": {},
   "source": [
    "The syntax here should look familiar; the first line ends with a\n",
    "colon, and the lines inside the `for` loop are indented. The other\n",
    "elements of the loop are:\n",
    "\n",
    "-   The words `for` and `in` are special words we have to use in a for\n",
    "    loop.\n",
    "\n",
    "-   `range` is a Python function we use to control the number of times the loop runs.\n",
    "\n",
    "-   `i` is a *loop variable* that gets created when the for loop runs.\n",
    "\n",
    "When this loop runs, it runs the statements inside the loop three times.  The first time, the value of `i` is `0`; the second time, it is `1`; the third time, it is `2`.\n",
    "\n",
    "Each time through the loop, it prints the value of `i` and moves one bike to Wellesley."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "breeding-groove",
   "metadata": {},
   "source": [
    "## TimeSeries\n",
    "\n",
    "When we run a simulation, we often want to save the results for later analysis. The ModSim library provides a `TimeSeries` object for this purpose. A `TimeSeries` contains a sequence of timestamps and a\n",
    "corresponding sequence of quantities.\n",
    "\n",
    "In this example, the timestamps are integers representing minutes and the quantities are the number of bikes at one location.\n",
    "\n",
    "Since we have moved a number of bikes around, let's start again with a new `State` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "every-consultation",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare = State(olin=10, wellesley=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cross-sharp",
   "metadata": {},
   "source": [
    "We can create a new, empty `TimeSeries` like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "changing-planet",
   "metadata": {},
   "outputs": [],
   "source": [
    "results = TimeSeries()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "attractive-revision",
   "metadata": {},
   "source": [
    "And we can add a quantity like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "aquatic-richardson",
   "metadata": {},
   "outputs": [],
   "source": [
    "results[0] = bikeshare.olin"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "searching-funeral",
   "metadata": {},
   "source": [
    "The number in brackets is the timestamp, also called a *label*.\n",
    "\n",
    "We can use a `TimeSeries` inside a for loop to store the results of the simulation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "english-titanium",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(3):\n",
    "    print(i)\n",
    "    step(0.6, 0.6)\n",
    "    results[i+1] = bikeshare.olin"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "prospective-joining",
   "metadata": {},
   "source": [
    "Each time through the loop, we print the value of `i` and call `step`, which updates `bikeshare`.\n",
    "Then we store the number of bikes at Olin in `results`. \n",
    "We use the loop variable, `i`, to compute the timestamp, `i+1`.\n",
    "\n",
    "The first time through the loop, the value of `i` is `0`, so the timestamp is `1`.\n",
    "The last time, the value of `i` is `2`, so the timestamp is `3`.\n",
    "\n",
    "When the loop exits, `results` contains 4 timestamps, from 0 through\n",
    "3, and the number of bikes at Olin at the end of each time step.\n",
    "\n",
    "We can display the `TimeSeries` like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "indonesian-singing",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "small-encoding",
   "metadata": {},
   "source": [
    "The left column is the timestamps; the right column is the quantities."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "following-contrary",
   "metadata": {},
   "source": [
    "## Plotting\n",
    "\n",
    "`results` provides a function called `plot` we can use to plot\n",
    "the results, and the ModSim library provides `decorate`, which we can use to label the axes and give the figure a title:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "saved-hands",
   "metadata": {},
   "outputs": [],
   "source": [
    "results.plot()\n",
    "\n",
    "decorate(title='Olin-Wellesley bikeshare',\n",
    "         xlabel='Time step (min)', \n",
    "         ylabel='Number of bikes')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "egyptian-korea",
   "metadata": {},
   "source": [
    "The result should be a plot with time on the $x$-axis and the number of bikes on the $y$-axis.\n",
    "Since we only ran three time steps, it might not be very interesting."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "limited-interstate",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This chapter introduces the tools we need to run simulations, record the results, and plot them.\n",
    "\n",
    "We used a `State` object to represent the state of the system.\n",
    "Then we used the `flip` function and an `if` statement to simulate a single time step.\n",
    "We used a `for` loop to simulate a series of steps, and a `TimeSeries` to record the results.\n",
    "Finally, we used `plot` and `decorate` to plot the results.\n",
    "\n",
    "In the next chapter, we will extend this simulation to make it a little more realistic."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fallen-surprise",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "Before you go on, you might want to work on the following exercises."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "capital-internship",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "What happens if you spell the name of a state variable wrong?  Edit the following cell, change the spelling of `wellesley`, and run it.\n",
    "\n",
    "The error message uses the word *attribute*, which is another name for what we are calling a state variable. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "helpful-zambia",
   "metadata": {},
   "outputs": [],
   "source": [
    "bikeshare = State(olin=10, wellesley=2)\n",
    "\n",
    "bikeshare.wellesley"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dirty-multiple",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    "Make a `State` object with a third state variable, called `downtown`, with initial value 0, and display the state of the system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "beneficial-mainland",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "christian-madrid",
   "metadata": {},
   "source": [
    "### Exercise 3\n",
    "\n",
    "Wrap the code in the chapter in a function named `run_simulation` that takes three parameters, named `p1`, `p2`, and `num_steps`.\n",
    "\n",
    "It should:\n",
    "\n",
    "1. Create a `TimeSeries` object to hold the results.\n",
    "\n",
    "2. Use a for loop to run `step` the number of times specified by `num_steps`, passing along the specified values of `p1` and `p2`.\n",
    "\n",
    "3. After each step, it should save the number of bikes at Olin in the `TimeSeries`.\n",
    "\n",
    "4. After the for loop, it should plot the results and\n",
    "\n",
    "5. Decorate the axes.\n",
    "\n",
    "To test your function:\n",
    "\n",
    "1. Create a `State` object with the initial state of the system.\n",
    "\n",
    "2. Call `run_simulation` with parameters `p1=0.3`, `p2=0.2`, and `num_steps=60`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "former-frost",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "spare-honduras",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "instructional-finnish",
   "metadata": {},
   "source": [
    "## Under the Hood\n",
    "\n",
    "This section contains additional information about the functions we've used and pointers to their documentation.\n",
    "\n",
    "You don't need to know anything in this section, so if you are already feeling overwhelmed, you might want to skip it.\n",
    "But if you are curious, read on."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "quick-citizen",
   "metadata": {},
   "source": [
    "`State` and `TimeSeries` objects are based on the `Series` object defined by the Pandas library.\n",
    "The documentation is at <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html>.\n",
    "\n",
    "`Series` objects provide their own `plot` function, which is why we call it like this:\n",
    "\n",
    "```\n",
    "results.plot()\n",
    "```\n",
    "\n",
    "Instead of like this:\n",
    "\n",
    "```\n",
    "plot(results)\n",
    "```\n",
    "\n",
    "You can read the documentation of `Series.plot` at <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.plot.html>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "digital-stretch",
   "metadata": {},
   "source": [
    "`decorate` is based on Matplotlib, which is a widely used plotting library for Python.  Matplotlib provides separate functions for `title`, `xlabel`, and `ylabel`.\n",
    "`decorate` makes them a little easier to use.\n",
    "For the list of keyword arguments you can pass to `decorate`, see <https://matplotlib.org/3.2.2/api/axes_api.html?highlight=axes#module-matplotlib.axes>.\n",
    "\n",
    "The `flip` function uses NumPy's `random` function to generate a random number between 0 and 1, then returns `True` or `False` with the given probability.\n",
    "\n",
    "You can get the source code for `flip` (or any other function) by running the following cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "agricultural-midwest",
   "metadata": {},
   "outputs": [],
   "source": [
    "source_code(flip)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "junior-lindsay",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
